import { cloneDeep, uniqueId } from "lodash";

const log = console.log.bind(console, '[IDP Msg]')

export async function listenIdpMsgOnce<T = any, P = any>(post: { action: string, value?: P }, acceptName = post.action) {
  const id = uniqueId()
  return new Promise<T>((res, rej) => {
    log('action:', post.action, '入参:', cloneDeep(post.value));
    const handler = (event: MessageEvent) => {
      if (event.data.action === 'error' && event.data.id === id) {
        console.error('[Catch IDP Error]', event.data);
        rej(event.data.value)
        window.removeEventListener('message', handler);
      } else if (event.data.action === acceptName && event.data.id === id) {
        log('action:', post.action, '出参', cloneDeep(event.data.value));
        res(event.data.value)
        window.removeEventListener('message', handler);
      }
    }
    window.addEventListener('message', handler)
    window.parent.postMessage({ id, ...post }, '*')
  })
}